import TauPage from '@/components/TauPage';
import TauActionPanel from '@/components/TauActionPanel';
import TauTable from '@/components/TauTable';
import { useStore } from '@/hooks';
import { Button, Drawer, Message, Checkbox } from '@alifd/next';
import { t } from '@lingui/macro';
import { uniqueId } from 'lodash';
import { observer } from 'mobx-react-lite';
import React, { useEffect, useRef, useState } from 'react';
import ChannelForm from './components/ChannelForm';
import { ENUMS, column, toSelectDataSource } from './stores/definitions';
import { toJS } from 'mobx';
import PriceScheme from './components/PriceScheme';
import ComponentsDrawer from '@/components/Drawers/ComponentsDrawer';
import Merchant from './components/Merchant';

const tableId = uniqueId('tauTable-');

function Channel() {
  const [modal, setModal] = useState([]);
  const [merchants, setMerchants] = useState([]);
  const { channelStore: store, loginStore } = useStore();
  const objRef = useRef(); // 当前选中的对象
  const [showOrders, setShowOrders] = useState(false);
  const [showCustomerMark, setShowCustomerMark] = useState(false);
  const [counts, setCounts] = useState({
    cc: [],
    bus: [],
    sc: [],
    rs: [],
    customerMark: [],
  });

  useEffect(() => {
    (async () => {
      await store.getCompany({ search: { status: 1 }, pg: { size: 999 } });
      await store.getDicts('channelType');
    })();
  }, []);

  useEffect(() => {
    if (showOrders) {
      (async () => {
        const cc = await fetchCCOrderCounts();
        const bus = await fetchBUSOrderCounts();
        const sc = await fetchSCOrderCounts();
        const rs = await fetchRSOrderCounts();
        setCounts({
          ...counts,
          cc,
          bus,
          sc,
          rs,
        });
      })();
    } else {
      setCounts({
        ...counts,
        cc: [],
        bus: [],
        sc: [],
        rs: [],
      });
    }
  }, [showOrders, store.data, store.from, store.to]);

  useEffect(() => {
    if (showCustomerMark) {
      (async () => {
        const res = await fetchCustomerMarkCounts();
        setCounts({
          ...counts,
          customerMark: res,
        });
      })();
    } else {
      setCounts({
        ...counts,
        customerMark: [],
      });
    }
  }, [showCustomerMark, store.data]);

  // 获取包车订单
  async function fetchCCOrderCounts() {
    const promiseAry = store.data.map(async (p) => {
      const merchant = await store.getMerchant(p?.id);
      return store.api
        .ordersCount({
          search: {
            merchantIds: merchant,
            orderType: 1,
            flag: '0',
            fromTime: store.from,
            toTime: store.to,
          },
        })
        .then((r) => ({ id: p.id, count: r }));
    });
    return Promise.all(promiseAry);
  }
  // 获取巴士订单
  async function fetchBUSOrderCounts() {
    const promiseAry = store.data.map(async (p) => {
      const merchant = await store.getMerchant(p?.id);
      return store.api
        .ordersCount({
          search: {
            merchantIds: merchant,
            orderType: 3,
            flag: '0',
            fromTime: store.from,
            toTime: store.to,
          },
        })
        .then((r) => ({ id: p.id, count: r }));
    });
    return Promise.all(promiseAry);
  }
  // 获取专线订单
  async function fetchSCOrderCounts() {
    const promiseAry = store.data.map(async (p) => {
      const merchant = await store.getMerchant(p?.id);
      return store.api
        .ordersCount({
          search: {
            merchantIds: merchant,
            orderType: 2,
            flag: '0',
            fromTime: store.from,
            toTime: store.to,
          },
        })
        .then((r) => ({ id: p.id, count: r }));
    });
    return Promise.all(promiseAry);
  }
  // 获取拼车订单
  async function fetchRSOrderCounts() {
    const promiseAry = store.data.map(async (p) => {
      const merchant = await store.getMerchant(p?.id);
      return store.api
        .ordersCount({
          search: {
            merchantIds: merchant,
            orderType: 4,
            flag: '0',
            fromTime: store.from,
            toTime: store.to,
          },
        })
        .then((r) => ({ id: p.id, count: r }));
    });
    return Promise.all(promiseAry);
  }
  // 获取拉新数量
  async function fetchCustomerMarkCounts() {
    const promiseAry = store.data.map(async (p) => {
      // 商户id
      const merchant = await store.merchantsSearch({ search: { associatedChannel: p?.id } });
      const inviteCodes = merchant.map((l) => `${l?.inviteCode}-8`);
      return store
        .getCustomers({
          search: {
            inviteCodes,
          },
        })
        .then((r) => ({
          id: p.id,
          count: r,
          inviteCodes,
        }));
    });
    return Promise.all(promiseAry);
  }

  // 获取列表数据
  const handleOnSearch = (params) => {
    const { channelDate, getOnDate, orderDate, ...searchArgs } = params.values;
    const [from, to] = channelDate || [];
    const [fromTime, toTime] = getOnDate || [];
    store.search = {
      from,
      to,
      fromTime,
      toTime,
      flag: '0',
      orderDate,
      ...searchArgs,
    };
  };

  // 点击打开添加
  const handleOpenAdd = () => {
    objRef.current = {};
    setModal(['add']);
  };

  // 点击打开查看
  const handleOpenView = (current) => {
    objRef.current = current;
    setModal(['view']);
  };

  // 点击打开编辑
  const handleOpenEdit = (current) => {
    objRef.current = current;
    setModal(['edit']);
  };

  // 打开价格方案
  const handleOpenPriceScheme = (channel) => {
    objRef.current = channel;
    setModal(['viewPrice']);
  };

  // Modal窗口关闭回调
  const handleCancel = () => {
    setModal([]);
  };

  // 变更数据提交
  const handleUpdate = async (result) => {
    if (!_.isEmpty(result)) {
      try {
        // if (result.discountInfo?.failureTime) {
        //   // eslint-disable-next-line no-param-reassign
        //   result.discountInfo.failureTime = moment.utc(result.discountInfo?.failureTime).subtract('8', 'hour').toISOString();
        // }
        // if (result.discountInfo?.disable) {
        //   result.discountInfo.disable = !result.discountInfo.disable;
        // }
        await store.update(toJS(result));
        Message.success({ content: t`修政成功` });
      } catch (e) {
        Message.error({ content: t`修政失败`, duration: 7000 });
        throw e;
      }
    }
    setModal([]);
  };

  // 新增订单数据提交
  const handleCreate = async (result) => {
    if (!_.isEmpty(result)) {
      try {
        // if (result.discountInfo?.failureTime) {
        //   // eslint-disable-next-line no-param-reassign
        //   result.discountInfo.failureTime = moment.utc(result.discountInfo?.failureTime).subtract('8', 'hour').toISOString();
        // }
        // if (result.discountInfo?.disable) {
        //   result.discountInfo.disable = !result.discountInfo.disable;
        // }
        await store.create({ ...toJS(result), attachments: result?.attachments || [] });
        Message.success({ content: t`渠道创建成功` });
      } catch (e) {
        Message.error({ content: t`渠道创建失败`, duration: 7000 });
        throw e;
      }
    }
    setModal([]);
  };

  // 点击跳转到详情
  const handleToChannel = async (record) => {
    const code = await loginStore.getCode();
    global.Cookie.set('code', code, { path: '/', maxAge: 60 }); // 有效期1分钟
    window.open(`${global.getEnvCfg().channelUrl}/?id=${record.id}`, 'channel');
  };

  // 查看商户
  const handleOpenMerChant = (result) => {
    objRef.current = result;
    setModal(['merchant']);
  };

  // 查看包车订单
  const handleOpenCCOrder = async (result) => {
    const merchant = await store.getMerchant(result?.id);
    objRef.current = result;
    setMerchants([...merchant]);
    setModal(['ccOrder']);
  };

  // 查看巴士订单
  const handleOpenBUSOrder = async (result) => {
    const merchant = await store.getMerchant(result?.id);
    objRef.current = result;
    setMerchants([...merchant]);
    setModal(['busOrder']);
  };

  // 查看专线订单
  const handleOpenSCOrder = async (result) => {
    const merchant = await store.getMerchant(result?.id);
    objRef.current = result;
    setMerchants([...merchant]);
    setModal(['scOrder']);
  };

  // 查看拼车订单
  const handleOpenRSOrder = async (result) => {
    const merchant = await store.getMerchant(result?.id);
    objRef.current = result;
    setMerchants([...merchant]);
    setModal(['rsOrder']);
  };

  // 查看客户信息
  const handleOpenCustomer = async (result) => {
    objRef.current = result;
    setModal(['customer']);
  };

  return (
    <TauPage className="page-container">
      <TauActionPanel
        onSearch={handleOnSearch}
        actions={[
          {
            name: 'btn-placeChannel',
            title: t`添加渠道`,
            type: 'primary',
            onClick: handleOpenAdd,
          },
        ]}
        searchItems={[
          {
            name: 'type',
            type: 'dict-item',
            props: { placeholder: t`渠道类型`, dictId: 'channelType' },
          },
          {
            name: 'state',
            type: 'select',
            props: {
              dataSource: toSelectDataSource(ENUMS.state),
              placeholder: t`启用状态`,
            },
          },
          {
            name: 'upDate',
            type: 'date-range',
            props: {
              placeholder: [t`起始更新时间`, t`结束更新时间`],
            },
          },
          {
            name: 'orderDate',
            type: 'date-range',
            props: {
              placeholder: [t`订单开始时间`, t`订单结束时间`],
            },
          },
        ]}
        extraItems={[
          {
            name: 'cbx-showOrders',
            component: <Checkbox style={{ marginLeft: 10 }} onChange={(v) => setShowOrders(v)}>{t`查看订单`}</Checkbox>,
          },
          {
            name: 'cbx-CustomerMarkCount',
            component: (
              <Checkbox style={{ marginLeft: 10 }} onChange={(v) => setShowCustomerMark(v)}>{t`查看客户绑定`}</Checkbox>
            ),
          },
        ]}
        keywordSearch={{
          // enabled: true,
          placeholder: t`请输入关键字搜搜`,
        }}
        className="action-panel"
      />
      <div className="content">
        <TauTable
          instanceId={tableId}
          primaryKey="id"
          tableLayout="fixed"
          currentPage={store.pg.page}
          pageSize={store.pg.size}
          total={store.total}
          sort={store.tableSort}
          onFetch={(pg) => {
            store.pg = pg;
          }}
          loading={store.loading}
          dataSource={toJS(store.data)}
          columns={[
            { title: t`序号`, dataIndex: 'idx', width: 44, cell: (v, i) => store.idx(i) },
            column('id', {
              width: 82,
              cell: (v, _, channel) => (
                <Button type="primary" text onClick={() => handleOpenView(channel)}>
                  {v}
                </Button>
              ),
            }),
            column('name', { width: 68 }),
            column('typeText', { width: 58 }),
            column('merchantCount', {
              width: 58,
              cell: (v, _, channel) => (
                <Button type="primary" text onClick={() => handleOpenMerChant(channel)}>
                  {v}
                </Button>
              ),
            }),
            column('ccOrderCount', {
              width: 88,
              cell: (v, _, channel) => (
                <Button type="primary" text onClick={() => handleOpenCCOrder(channel)}>
                  {counts.cc.find((n) => n.id === channel.id)?.count || 0}
                </Button>
              ),
            }),
            column('busOrderCount', {
              width: 88,
              cell: (v, _, channel) => (
                <Button type="primary" text onClick={() => handleOpenBUSOrder(channel)}>
                  {counts.bus.find((n) => n.id === channel.id)?.count || 0}
                </Button>
              ),
            }),
            column('scOrderCount', {
              width: 88,
              cell: (v, _, channel) => (
                <Button type="primary" text onClick={() => handleOpenSCOrder(channel)}>
                  {counts.sc.find((n) => n.id === channel.id)?.count || 0}
                </Button>
              ),
            }),
            column('rsOrderCount', {
              width: 88,
              cell: (v, _, channel) => (
                <Button type="primary" text onClick={() => handleOpenRSOrder(channel)}>
                  {counts.rs.find((n) => n.id === channel.id)?.count || 0}
                </Button>
              ),
            }),
            column('customerMarkCount', {
              width: 88,
              cell: (v, _, channel) => (
                <Button type="primary" text onClick={() => handleOpenCustomer(channel)}>
                  {counts.customerMark.find((n) => n.id === channel.id)?.count || 0}
                </Button>
              ),
            }),
            column('state', { width: 88 }),
            column('orderCommissionTotal', { width: 88 }),
            column('upDate', { width: 88, sortable: true }),
            {
              title: t`操作`,
              dataIndex: 'channelNumber',
              width: 180,
              cell: (_, __, channel) => (
                <>
                  <Button text type="primary" onClick={() => handleOpenEdit(channel)}>{t`编辑`}</Button>
                  <span style={{ color: 'var(--btn-text-primary-color, #5584FF)' }}> | </span>
                  <Button text type="primary" onClick={() => handleOpenPriceScheme(channel)}>{t`价格方案`}</Button>
                  <span style={{ color: 'var(--btn-text-primary-color, #5584FF)' }}> | </span>
                  <Button text type="primary" onClick={() => handleToChannel(channel)}>{t`详情`}</Button>
                </>
              ),
            },
          ]
            .filter((c) => c.dataIndex !== 'ccOrderCount' || showOrders)
            .filter((c) => c.dataIndex !== 'busOrderCount' || showOrders)
            .filter((c) => c.dataIndex !== 'scOrderCount' || showOrders)
            .filter((c) => c.dataIndex !== 'rsOrderCount' || showOrders)
            .filter((c) => c.dataIndex !== 'customerMarkCount' || showCustomerMark)}
        />
      </div>
      <Drawer
        visible={modal[0] === 'add' || modal[0] === 'edit' || modal[0] === 'view'}
        title={modal[0] === 'add' ? t`添加渠道` : t`修改渠道【${objRef.current?.name}】`}
        style={{ maxWidth: '90%' }}
        closeMode={['esc', 'mask', 'close']}
        onClose={() => setModal([...modal, `toClose$${Date.now()}`])}
        width="90%"
      >
        <ChannelForm
          channelId={objRef.current?.id}
          modal={modal}
          onCancel={handleCancel}
          onSubmit={modal[0] === 'add' ? handleCreate : handleUpdate}
        />
      </Drawer>
      <Drawer
        visible={modal[0] === 'viewPrice'}
        title={modal[0] === 'viewPrice' && t`查看【${objRef.current?.name}】价格方案`}
        style={{ maxWidth: '90%' }}
        closeMode={['esc', 'mask', 'close']}
        onClose={() => setModal([...modal, `toClose$${Date.now()}`])}
        width="90%"
      >
        <PriceScheme
          channelId={objRef.current?.id}
          modal={modal}
          onCancel={handleCancel}
          onSubmit={modal[0] === 'add' ? handleCreate : handleUpdate}
        />
      </Drawer>
      <Drawer
        visible={modal[0] === 'merchant'}
        title={t`查看${objRef.current?.name}商户`}
        style={{ maxWidth: '90%' }}
        closeMode={['esc', 'mask', 'close']}
        onClose={() => setModal([...modal, `toClose$${Date.now()}`])}
        width="90%"
      >
        <Merchant
          channel={{ associatedChannel: objRef.current?.id }}
          modal={modal}
          onCancel={handleCancel}
          onSubmit={() => {}}
        />
      </Drawer>
      <ComponentsDrawer
        modal={modal}
        queryParams={{ merchantIds: merchants }}
        inviteCodes={counts.customerMark.find((p) => p.id == objRef.current?.id)?.inviteCodes || []}
        name={objRef.current?.name}
        onCancel={handleCancel}
      />
    </TauPage>
  );
}

export default observer(Channel);
